'use strict';
import Utf8 from 'crypto-js/enc-utf8';
import AES from 'crypto-js/aes';
import ECB from 'crypto-js/mode-ecb';
import Pkcs7 from 'crypto-js/pad-pkcs7';


/**
 * @method initAes
 * @description 初始化Aes加密工具
 * @author yanghaiyang
 * @date 2021-07-02 16:07:51
 * @param {string} [keyStr] 密钥 默认值'4e8759c58fdb413dcc2c243eebab91f6'
 * @param {number} [n] 位数 默认值9
 * @returns {string} aseKey
 */
export function initAes (keyStr = '4e8759c58fdb413dcc2c243eebab91f6', n = 9) {
  if (keyStr.length < n) {
    throw new Error('n过大');
  }
  return keyStr.substr(n).concat(keyStr.substr(0, n));
}


/**
 * @method encrypt
 * @description Aes加密
 * @author yanghaiyang
 * @date 2021-07-02 16:07:31
 * @param {string} [word] 待加密文本
 * @param {string} [aesKey] 预先生成的aeskey
 * @returns {string} 加密后的结果
 */
export function encrypt (word:string, aesKey: string) {
  const key = Utf8.parse(aesKey),
    srcs = Utf8.parse(word),
    encrypted = AES.encrypt(srcs, key, {
      mode: ECB,
      padding: Pkcs7
    });
  return encrypted.toString();
}

/**
 * @method decrypt
 * @description Aes解密
 * @author yanghaiyang
 * @date 2021-07-02 16:07:32
 * @param {string} [word] 待解密的文本
 * @param {string} [aesKey] 预先生成的aeskey
 * @returns {string} 解密后的结果
 */
export function decrypt (word: string, aesKey: string) {
  const key = Utf8.parse(aesKey),
    decrypt = AES.decrypt(word, key, {
      mode: ECB,
      padding: Pkcs7
    });
  let decWord = word;
  try {
    decWord = Utf8.stringify(decrypt).toString();
  } catch (e) {}
  return decWord;
}

